package util

import (
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

// 全局日志管理
var Logger *zap.Logger

func init() {
	logEncoder := getEncoder()
	logWriter := getWriteSync()

	core := zapcore.NewCore(logEncoder, logWriter, zapcore.InfoLevel)
	Logger = zap.New(core)
}

// 负责设置 encoding 的日志格式
func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder

	return zapcore.NewConsoleEncoder(encoderConfig)
}

// 负责日志写入的位置
func getWriteSync() zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   "./log.txt",
		MaxSize:    10,
		MaxBackups: 50,
		MaxAge:     30,
		Compress:   false,
	}
	jackLogger := zapcore.AddSync(lumberJackLogger)

	syncConsole := zapcore.AddSync(os.Stderr) // 写入到标准输出
	return zapcore.NewMultiWriteSyncer(jackLogger, syncConsole)
}
